import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import './index.css';

type SquareValue = "X" | "O" | null;

type SquareProps = {
  value: SquareValue;
  onSquareClick: () => void;
};

function Square({ value, onSquareClick }: SquareProps) {
  return <button className="square" onClick={onSquareClick}>{value}</button>;
}

type BoardProps = {
  xIsNext: boolean;
  squares: SquareValue[];
  onPlay: (nextSquares: SquareValue[]) => void;
  onReset: () => void;
};

function Board({ xIsNext, squares, onPlay }: BoardProps) {
  const winner = calculateWinner(squares);
  if (winner) {
    status = "获胜者: " + winner;
  } else {
    status = "下一步的玩家: " + (xIsNext ? "X" : "O");
  }

  function handleClick(i: number) {
    if (squares[i] || calculateWinner(squares)) {
      return;
    }
    const nextSquares = squares.slice();
    nextSquares[i] = xIsNext ? "X" : "O";
    onPlay(nextSquares);
  }

  return (
    <div className="wrapper">
      <div className="board-row">
        <Square value={squares[0]} onSquareClick={() => handleClick(0)} />
        <Square value={squares[1]} onSquareClick={() => handleClick(1)} />
        <Square value={squares[2]} onSquareClick={() => handleClick(2)} />
      </div>
      <div className="board-row">
        <Square value={squares[3]} onSquareClick={() => handleClick(3)} />
        <Square value={squares[4]} onSquareClick={() => handleClick(4)} />
        <Square value={squares[5]} onSquareClick={() => handleClick(5)} />
      </div>
      <div className="board-row">
        <Square value={squares[6]} onSquareClick={() => handleClick(6)} />
        <Square value={squares[7]} onSquareClick={() => handleClick(7)} />
        <Square value={squares[8]} onSquareClick={() => handleClick(8)} />
      </div>
    </div>
  );
}

function calculateWinner(squares: SquareValue[]): SquareValue {
  const lines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ];

  for (let i = 0; i < lines.length; i++) {
    const [a, b, c] = lines[i];
    if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
      return squares[a];
    }
  }

  return null;
}

function Game() {
  const navigate = useNavigate();
  const [xIsNext, setXIsNext] = useState(true);
  const [currentMove, setCurrentMove] = useState(0);
  const [history, setHistory] = useState([Array(9).fill(null)]);
  const currentSquares = history[currentMove];

  useEffect(() => {
    document.title = '井字棋游戏';
  }, []);

  function handlePlay(nextSquares: SquareValue[]) {
    const nextHistory = [...history.slice(0, currentMove + 1), nextSquares];
    setHistory(nextHistory);
    setCurrentMove(nextHistory.length - 1);
    setXIsNext(!xIsNext);
  }

  function jumpTo(nextMove: number) {
    setCurrentMove(nextMove);
    setXIsNext(nextMove % 2 === 0);
  }

  function resetGame() {
    setHistory([Array(9).fill(null)]);
    setCurrentMove(0);
    setXIsNext(true);
  }

  const winner = calculateWinner(currentSquares);
  const status = winner ? `获胜者: ${winner}` : `下一步的玩家: ${xIsNext ? 'X' : 'O'}`;

  const moves = history.map((squares, move) => {
    const description = move > 0 ? `第 ${move} 步操作：` : '开始游戏';
    console.log(squares)
    return (
      <div
        key={move}
        className="history-item"
        onClick={() => jumpTo(move)} // 可点击回到该步
      >
        <span className="history-description">{description}</span>
        {move > 0 && <span className="history-action">回到这一步</span>}
      </div>
    );
  });

  return (
    <div className="game">
      <div className="game-container">
        {/* 第一行：开始新的一局 */}
        <div className="game-top">
          <button onClick={resetGame} className="reset-button">开始新的一局</button>
          <button onClick={() => navigate('/')} className="goback-button">回到首页</button>
        </div>

        {/* 第二行：状态 */}
        <div className="game-status">{status}</div>

        {/* 第三行：棋盘 */}
        <Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} onReset={resetGame} />

        {/* 第四行：历史记录，两列 */}
        <div className="game-history">
          {moves.map((move, index) => (
            <div key={index} className="history-item">{move}</div>
          ))}
        </div>

      </div>
    </div>
  );
}

export default Game;
